<template>
  <el-form
    class="apply-form first-form"
    :model="codeLogin"
    :rules="codeLoginRules"
    ref="codeLogin"
  >
    <el-form-item prop="email">
      <el-input
        type="text"
        v-model="codeLogin.email"
        :class="{ haveValue: codeLogin.email }"
        placeholder="请输入邮箱"
      ></el-input>
    </el-form-item>
    <el-form-item prop="code" :error="codeErrorMessage">
      <el-input
        type="text"
        placeholder="请输入验证码"
        v-model="codeLogin.code"
        :class="{ haveValue: codeLogin.code }"
        @keyup.enter.native="handelEnterKey"
      ></el-input>
      <div class="fetchCodeBox">
        <button class="fetchCode" @click.prevent="checkEmailField">
          {{ codeLastTime ? codeLastTime + "秒" : "获取验证码" }}
        </button>
      </div>
      <div class="codeTips" v-show="showCodeTips">验证码已发送至邮箱</div>
    </el-form-item>
    <div class="autoLoginBox">
      <div class="checkAutoLogin">
        <el-checkbox
          label="7天内自动登录"
          v-model="codeLogin.autoLogin"
          name="type"
        ></el-checkbox>
      </div>
      <!-- <div class="findAcoount">找回账号</div> -->
    </div>
    <el-form-item>
      <el-button
        type="primary"
        class="loginBtn"
        :loading="load"
        @click="verificationValue"
        >登录</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { login, sendVaildCode, checkVaildCode } from "@/request/user";
import md5 from "js-md5";
export default {
  data() {
    return {
      // 验证码登录参数
      codeLogin: {
        email: "",
        code: "",
        autoLogin: false,
      },
      // 验证码登录验证
      codeLoginRules: {
        email: [
          {
            required: true,
            message: "请输入正确的邮箱地址",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
        ],
      },
      load: false,
      loging: false, // 防止控制多次请求
      codeLastTime: 0, // 验证码剩余时间
      showCodeTips: false, // 显示已获取验证码提示
      codeErrorMessage: "", // 验证码服务器验证错误提示
    };
  },
  created() {
    this.handleGetLastTime();
  },
  methods: {
    // 设置发送验证码剩余时间
    handleGetLastTime() {
      let sendRegCodeLastTime = localStorage.getItem("lRCLT");
      const currTime = new Date().getTime();
      if (sendRegCodeLastTime === null) {
        this.codeLastTime = 0;
        return;
      }
      if (currTime - sendRegCodeLastTime < 60000) {
        this.handelFetchCode(
          60 - Math.ceil((currTime - sendRegCodeLastTime) / 1000)
        );
      } else {
        localStorage.removeItem("lRCLT");
      }
    },
    // 获取验证码
    handelFetchCode(time) {
      this.showCodeTips = true;
      // 如果验证码已发送倒计时没结束则退出
      this.codeLastTime = time;
      let lassTimer = setInterval(() => {
        --this.codeLastTime;
        // 清除计时器
        if (this.codeLastTime === 0) {
          clearInterval(lassTimer);
          lassTimer = null;
          localStorage.removeItem("lRCLT");
        }
      }, 1000);
    },
    // 验证邮箱字段
    checkEmailField() {
      this.$refs["codeLogin"].validateField("email", (res) => {
        // 如果返回的错误信息为空
        if (res === "") {
          this.sendCode();
        }
      });
    },
    // 按下回车键
    handelEnterKey() {
      this.verificationValue();
    },
    // 登录前验证参数
    verificationValue() {
      this.$refs["codeLogin"].validate((valid) => {
        if (valid) {
          this.handelLogin();
        } else {
          return false;
        }
      });
    },
    // 请求登录接口
    async handelLogin() {
      // 如果正在登录中 终止此次登录
      if (this.loging) return;
      const params = {
        userName: this.codeLogin.email,
        code: this.codeLogin.code,
        isRemember: this.codeLogin.autoLogin, // 7天内自动登录
      };
      if (this.codeLogin.email == "" || this.codeLogin.code == "") {
        this.$message({
          message: "用户名或密码不能为空",
          type: "warning",
        });
        return;
      }
      this.load = true;
      this.loging = true;
      let a = await this.$store.dispatch("user/Login", {
        params: params,
        this: this,
      });
      this.load = false
      if (a) {
        if (this.$refs.codeLogin) this.$refs.codeLogin.resetFields();
        const routerParams = this.$router.currentRoute.params;
        if (routerParams.rediretUrl) return window.location.href = routerParams.rediretUrl
        if (routerParams.routePath || routerParams.query) {
          this.$router.replace({
            path: routerParams.routePath,
            query: routerParams?.query,
          });
        } else {
          this.$router.replace({ name: "Home" });
        }
      } else {
        this.loging = false;
      }
    },
    // 发送验证码
    sendCode() {
      // // 查看剩余时间
      if (this.codeLastTime) return;
      const params = { userMail: this.codeLogin.email };
      sendVaildCode(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: `验证码已发送至邮箱，验证码有效时间${
              res.data.duration / 60
            }分钟！`,
          });
          localStorage.setItem("lRCLT", new Date().getTime());
          this.handelFetchCode(60);
        } else {
          this.$antdMessage.error({
            content: res.message || res,
          });
        }
      });
    },
    // 验证验证码是否正确 登录不需要验证验证码
    // checkCode() {
    //   const params = {
    //     userMail: this.codeLogin.email,
    //     code: this.codeLogin.code,
    //   };
    //   checkVaildCode(params).then((res) => {
    //     if (res.errno === 0) {
    //     } else {
    //       this.$nextTick(() => {
    //         this.codeErrorMessage = res.message || "验证码错误";
    //       });
    //     }
    //   });
    // },
  },
};
</script>

<style lang="stylus">
.codeLoginBox {
  .fetchCodeBox {
    position: absolute;
    right: 8px;
    top: 10px;
    height: 20px;
    line-height: 20px;

    button {
      cursor: pointer;
      padding: 0;
      padding-left: 6px;
      min-width: 77px;
      text-align: center;
      outline: none;
      height: 20px;
      line-height: 20px;
      border: none;
      border-left: 1px dashed #909090;
      background: transparent;
      font-family: Segoe UI;
      font-size: 14px;
      color: #0e79c0;
      opacity: 0.6;
    }
  }

  .autoLoginBox {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .checkAutoLogin {
      .el-checkbox {
        .el-checkbox__label {
          font-family: Segoe UI;
          font-size: 12px;
          color: #707070;
          opacity: 0.6;
        }

        .el-checkbox__inner:hover {
          border-color: #d9d7d7;
        }

        .is-checked {
          .el-checkbox__inner {
            background: #ececec;
            border-color: #d9d7d7;
          }

          .el-checkbox__inner::after {
            color: #3d3d3d;
            border-color: #3d3d3d;
            border-width: 2px;
          }
        }

        .el-checkbox__input, .is-focus {
          border-color: #d9d7d7;

          .el-checkbox__inner {
            border-color: #d9d7d7;
          }
        }
      }
    }

    .findAcoount {
      font-family: Segoe UI;
      font-size: 12px;
      color: #707070;
      opacity: 0.6;
    }
  }

  .codeTips {
    bottom: -15px;
    position: absolute;
    right: 0;
    line-height: 1;
    font-size: 12px;
    color: #707070;
  }
}
</style>